package com.kevin.jetcache.service;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.alicp.jetcache.anno.CreateCache;
import com.kevin.jetcache.dto.UserDto;
import lombok.val;
import org.springframework.stereotype.Service;

/**
 * @author Kevin Liu
 * @date 2020/8/14 上午10:02
 */
@Service
public class UserService {

    @CreateCache(name = "UserService.userCache", expire = 100, cacheType = CacheType.BOTH, localLimit = 50)
    private Cache<Long, UserDto> userCache;

    public void insertUser(UserDto userDto) {
        userCache.put(userDto.getId(),userDto);
    }

    public void  delUser(Long userId) {
        userCache.remove(userId);
    }

    public UserDto findById(Long userId){
        return userCache.computeIfAbsent(userId,id->{
            val userDto = new UserDto();
            //这里可以从数据库查
            userDto.setId(id);
            userDto.setName("spy");
            userDto.setAge(23);
            return userDto;
        });
    }

    /**
     * 测试方法缓存
     * @param userId
     * @return
     * @throws InterruptedException
     */
    @Cached(name="UserService.getUserById", expire = 3600)
    public UserDto getUserById(Long userId) throws InterruptedException {
        Thread.sleep(2000);
        val userDto = new UserDto();
        userDto.setId(userId);
        userDto.setName("spy");
        userDto.setAge(23);
        return userDto;
    }
}
